package com.tutucms.service.admin.controller;

import com.tutucms.common.exception.InvokException;
import com.tutucms.common.model.response.ResponseResult;
import com.tutucms.common.util.CharUtil;
import com.tutucms.common.util.ConfigFileUtil;
import com.tutucms.service.admin.service.OssService;
import com.tutucms.service.model.vo.AliOssInfoVo;
import com.tutucms.service.model.vo.AliStsInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangxudong on 2020/03/07.
 *
 * @version: 1.0
 * @modified :
 */
@Slf4j
@RestController
@RequestMapping(value = "/storage")
@Api(value = "存储模块", tags = "存储模块")
public class StorageController {

    private static String ueditorConfigCache = "";

    @Autowired
    private OssService ossService;

    @ApiOperation(value = "上传单个文件")
    @PostMapping("/store")
    public ResponseResult<String> sotre(@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String url;
        try {
            url = ossService.store(file.getInputStream(), file.getSize(),
                    file.getContentType(), originalFilename);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new InvokException("文件上传失败:" + e.getMessage());
        }

        return ResponseResult.successResult(url);
    }

    @ApiOperation(value = "上传多个文件")
    @PostMapping("/stores")
    public ResponseResult<List<String>> sotres(HttpServletRequest request) {
        List<String> urls = new ArrayList<>();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

        MultipartFile file;
        for (MultipartFile multipartFile : files) {
            file = multipartFile;
            if (!file.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                try {
                    urls.add(ossService.store(file.getInputStream(), file.getSize(),
                            file.getContentType(), originalFilename));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                    throw new InvokException("文件上传失败:" + e.getMessage());
                }
            }
        }

        return ResponseResult.successResult(urls);
    }

    @ApiOperation(value = "获取阿里云sts")
    @GetMapping("/getAliSts")
    public ResponseResult<AliStsInfoVo> getAliSts() {

        return ResponseResult.successResult(ossService.fetchAliYunOssSts());
    }

    @ApiOperation("获取阿里云OSS信息,建议每次启动应用程序调用")
    @GetMapping("/getAliOssInfo")
    public ResponseResult<AliOssInfoVo> getAliOssInfo() {
        AliOssInfoVo infoVo = new AliOssInfoVo();
        infoVo.setBucketName(ossService.getAliOssConfig().getBucketName());
        infoVo.setOssHostName(ossService.getAliOssConfig().getHostName());
        infoVo.setOssEndpoint(ossService.getAliOssConfig().getEndpoint());

        return ResponseResult.successResult(infoVo);
    }

    @ApiOperation(value = "ueditor")
    @ResponseBody
    @RequestMapping(value = "/ueditor", produces = "application/json;charset=UTF-8")
    public Object ueditorConfig(@Param("action") String action, HttpServletRequest request) {

        if ("config".equals(action)) {
            if (CharUtil.isEmpty(ueditorConfigCache)) {
                ueditorConfigCache = ConfigFileUtil.readCharFileFromResource("ueditor_config.json");
            }

            return ueditorConfigCache;
        } else {
            Map<String, String> map = new HashMap<>();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("upfile");
            MultipartFile file = files.get(0);
            String url = "";
            try {
                String originalFilename = file.getOriginalFilename();
                url = ossService.store(file.getInputStream(), file.getSize(),
                        file.getContentType(), originalFilename);

                map.put("url", url);
                map.put("state", "SUCCESS");
                map.put("original", "");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                map.put("url", url);
                map.put("state", "FAILURE");
                map.put("original", "");
                throw new InvokException("文件上传失败:" + e.getMessage());
            }
            return map;
        }

    }


}
